nutanixPortal
  .controller('virtualMachineCtrl', function ($scope, $filter, $http, ngTableParams, $uibModal, growlService, ENV){
    

    //config data
    $scope.config = {
      num: 10,
      pattern: 'qcow2'
    };
    $scope.plus = function(num) {
      $scope.config.num += num;
    }
    $scope.data = {
      mirrors: [
        'CentOS 6.4 64bit',
        'CentOS 6.5 64bit',
        'CentOS 6.6 64bit',
        'CentOS 6.7 64bit',
        'CentOS 7.0 64bit',
        'CentOS 7.1 64bit',
        'CentOS 7.2 64bit',
        'Ubuntu 14.04 64bit',
        'Ubuntu 15.04 64bit',
        'Fedora 20 64bit',
        'Fedora 21 64bit',
        'Fedora 22 64bit',
        'Windows Server 2003',
        'Windows Server 2008',
      ],
      cpus: [
        '1v CPU',
        '2v CPU',
        '4v CPU',
        '8v CPU',
        '16v CPU'
      ],
      memories: ['2G', '4G', '8G', '16G'],
      networks: ['public', 'private', 'nxtcloud'],
      filesyses: ['raw', 'qcow2', 'qed', 'vdi', 'vmdk', 'vhd'],
      dbsyses: ['mysql', 'oracle', 'sqlserver'],
      disks: ['256G', '512G', '1T', '2T', '4T']
    };

    //更新虚拟机情况
    $scope.refresh = function () {

      $http({
        method: 'GET',
        url: ENV.apiUrl + 'vms/',
      }).then(function successCallback(response){
        //data table
        var data = [];
        var entities = response.data.entities;
        for (var i = 0; i < entities.length; i++) {
          if(entities[i].controllerVm == false){
            data.push(entities[i]);
          }
        };

        //Sorting, 组织数据
        $scope.vmTable = new ngTableParams({
          page: 1,            // show first page
          count: 10,           // count per page
        }, {
          total: data.length, // length of data
          getData: function($defer, params) {
            // use build-in angular filter
            var orderedData = params.sorting() ? $filter('orderBy')(data, params.orderBy()) : data;
            $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
          }
        })

      });
    }
    $scope.refresh();


    //查询获取虚拟机信息
    $scope.getVMInfos = function (vmId) {
      //获取硬盘信息
      $http({
        method: 'GET',
        url: ENV.apiUrl + 'vms/' + vmId + '/virtual_disks',
      }).then(function successCallback(response){
        //data table
        var data = response.data.entities;
        getSortTable('diskTable', data);
      });

      //获取网络信息
      $http({
        method: 'GET',
        url: ENV.apiUrl + 'vms/' + vmId + '/virtual_nics',
      }).then(function successCallback(response){
        //data table
        var data = response.data;
        getSortTable('nicTable', data);
      });

      //获取快照信息
      $http({
        method: 'GET',
        url: ENV.apiV8 + 'vms/' + vmId + '/snapshots?includeSnapshots=true',
      }).then(function successCallback(response){
        //data table
        var data = response.data.linkList;
        getSortTable('snapshotTable', data);
      });

      //获取任务信息
      $http({
        method: 'GET',
        url: ENV.apiV8 + 'tasks?entityUuids=' + vmId + '&includeCompleted=true&includeEntityNames=true',
      }).then(function successCallback(response){
        //data table
        var data = response.data.linkList;
        getSortTable('taskTable', data);
      });
      
    }

    function getSortTable(resTable, data) {
      //Sorting, 组织数据
      $scope[resTable] = new ngTableParams({
        page: 1,            // show first page
        count: 10,           // count per page
      }, {
        total: data.length, // length of data
        getData: function($defer, params) {
          // use build-in angular filter
          var orderedData = params.sorting() ? $filter('orderBy')(data, params.orderBy()) : data;
          $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
        }
      })
    }


    //modal
    $scope.openModal = function(){
      $uibModal.open({
        animation: true,
        templateUrl: '/views/virtualMachineModal.html',
        controller: 'virtualMachineModalCtrl',
        backdrop: 'static',
        resolve: {
          content: function () {
            return $scope.modalContent;
          }
        }
      });
    };

    //toggle nav right menus
    $scope.isOpen = 0;
    $scope.toggle = function (index) {
      $scope.isOpen = index;
    }
    $scope.status = function (index) {
      return $scope.isOpen == index;
    }
    $scope.navOpen = false;
    $scope.navOpenId = '';
    $scope.closeRightNav = function () {
      $scope.navOpen = false;
    }
    $scope.toggleRightNav = function (vmId) {
      if($scope.navOpenId != vmId || $scope.navOpen == false){
        $scope.navOpenId = vmId;
        $scope.navOpen = true;
        $scope.getVMInfos(vmId);
      }
      else{
        $scope.navOpen = false;
      }
    }

    //host operation by swalling
    //pause
    $scope.pause = function(){
      growlService.growl("服务器已挂起！", "success");
    };

    //resume
    $scope.resume = function(){
      growlService.growl("服务器已恢复！", "success");
    };

    //start up host
    $scope.startup = function(){
      growlService.growl("开机成功！", "success");
    };

    //shutdown host
    $scope.shutdown = function(){
      swal({   
          title: "你确定要关机吗?",   
          text: "关机后将会影响正在运行的服务，请确认!",   
          type: "warning",   
          showCancelButton: true,   
          confirmButtonColor: "#DD6B55",   
          confirmButtonText: "确定关机!",   
          closeOnConfirm: false 
      }, function(){   
          swal("关机中...", "", "success"); 
      });
    };

    //restart host
    $scope.restart = function(){
      swal({   
          title: "你确定要重启吗?",   
          text: "重启后将会影响正在运行的服务，请注意!",   
          type: "warning",   
          showCancelButton: true,   
          confirmButtonColor: "#DD6B55",   
          confirmButtonText: "确定重启!",   
          closeOnConfirm: false 
      }, function(){   
          swal("重启中...", "请稍等", "success"); 
      });
    };

    //delete host
    $scope.delete = function(){
      swal({   
          title: "你确定要删除吗?",   
          text: "删除后将无法复原，请注意！",   
          type: "warning",   
          showCancelButton: true,   
          confirmButtonColor: "#DD6B55",   
          confirmButtonText: "确定删除!",   
          closeOnConfirm: false 
      }, function(){   
          swal("已删除...", "", "success"); 
      });
    };

    //创建快照modal
    $scope.openSnapshotModal = function(){
      $uibModal.open({
        animation: true,
        templateUrl: '/views/virtualMachineImg.html',
        controller: 'virtualMachineImgCtrl',
        backdrop: 'static',
      });
    };

    //更改配置modal
    $scope.openUpdateModal = function(){
      $uibModal.open({
        animation: true,
        templateUrl: '/views/virtualMachineUpdate.html',
        controller: 'virtualMachineUpdateCtrl',
        backdrop: 'static',
      });
    };

    //迁移modal
    $scope.openMigrateModal = function(){
      $uibModal.open({
        animation: true,
        templateUrl: '/views/virtualMachineMigrate.html',
        controller: 'virtualMachineMigrateCtrl',
        backdrop: 'static',
      });
    };

    //修改密码modal
    $scope.openModifyPwdModal = function(){
      $uibModal.open({
        animation: true,
        templateUrl: '/views/virtualMachinePwd.html',
        controller: 'virtualMachinePwdCtrl',
        backdrop: 'static',
      });
    };

    //绑定IP
    $scope.openLockIPModal = function(){
      $uibModal.open({
        animation: true,
        templateUrl: '/views/virtualMachineIP.html',
        controller: 'virtualMachineIPCtrl',
        backdrop: 'static',
      });
    };

    //解绑IP
    $scope.unlockIP = function(){
      swal({   
          title: "你确定要解绑此IP吗?",   
          text: "解绑后网络服务将无法使用，请注意!",   
          type: "warning",   
          showCancelButton: true,   
          confirmButtonColor: "#DD6B55",   
          confirmButtonText: "确定解绑!",   
          closeOnConfirm: false 
      }, function(){   
          swal("解绑中...", "请稍等", "success"); 
      });
    };



  })
  .controller('virtualMachineModalCtrl', function ($scope, $uibModalInstance, vmService, growlService){
    $scope.cancel = function () {
      $uibModalInstance.dismiss('cancel');
    };

    $scope.step = 1;
    function slide(step) {
      $("#slide-wrapper").stop(true,false)
        .animate({"left": -600 * (step - 1) }, 500);
    }
    $scope.goNext = function () {
      
      $scope.step++;
      slide($scope.step);
    };
    $scope.goPre = function () {
      
      $scope.step--;
      slide($scope.step);
    };
    $scope.finish = function () {
      // vmService.addVM($scope.config.name, $scope.config.host, $scope.config.ip, 
      //   $scope.config.cpu, $scope.config.memory, $scope.config.disks);
      $uibModalInstance.close();
    };

    $scope.data = {
      mirrors: [
        'CentOS 6.4 64bit',
        'CentOS 6.5 64bit',
        'CentOS 6.6 64bit',
        'CentOS 6.7 64bit',
        'CentOS 7.0 64bit',
        'CentOS 7.1 64bit',
        'CentOS 7.2 64bit',
        'Ubuntu 14.04 64bit',
        'Ubuntu 15.04 64bit',
        'Fedora 20 64bit',
        'Fedora 21 64bit',
        'Fedora 22 64bit',
        'Windows Server 2003',
        'Windows Server 2008',
      ],
      networks: ['public', 'private', 'nxtcloud'],
    };

    $scope.regex = '\\d+';
    $scope.ipRegex = '\\d+.\\d+.\\d+.\\d+';

    $scope.config = {
      name: '',
      host: '',
      mirror: 'CentOS 6.4 64bit',
      cpu: '',
      coresPerCPU: '1',
      memory: '',
      network: '',
      ip: '',
      user: '',
      pwd: '',
      disks: []
    };

    var indexPool = [0, 1, 2];
    $scope.addDisk = function (){
      $scope.config.disks.push({
        id: indexPool.pop(),
        type: 'disk',
        busType: 'scsi',
        container: 'default',
        size: '',
      })
    }
    $scope.deleteDisk = function (id){
      for(var i = 0; i < $scope.config.disks.length; i++){
        if($scope.config.disks[i].id == id){
          $scope.config.disks.splice(i, 1);
          indexPool.push(id);
          break;
        }
      }
    }

  })
  .controller('virtualMachineImgCtrl', function ($scope, $uibModalInstance, growlService){
    $scope.cancel = function () {
      $uibModalInstance.dismiss('cancel');
    };

    $scope.finish = function () {
      growlService.growl("快照创建成功！", "success");
      $uibModalInstance.close();
    };

    $scope.data = {
      types: ['normal', 'huge', 'specil']
    };

    $scope.config = {
      name: '',
      type: 'normal'
    };
  })
  .controller('virtualMachineMigrateCtrl', function ($scope, $uibModalInstance, growlService){
    $scope.cancel = function () {
      $uibModalInstance.dismiss('cancel');
    };

    $scope.finish = function () {
      growlService.growl("迁移至主机成功！", "success");
      $uibModalInstance.close();
    };

    $scope.data = {
      hosts: ['host1', 'host2', 'host3']
    };

    $scope.config = {
      host: '',
    };
  })
  .controller('virtualMachinePwdCtrl', function ($scope, $uibModalInstance, growlService){
    $scope.cancel = function () {
      $uibModalInstance.dismiss('cancel');
    };

    $scope.step = 1;
    function slide(step) {
      $("#slide-wrapper").stop(true,false)
        .animate({"left": -600 * (step - 1) }, 500);
    }
    $scope.goNext = function () {
      $scope.config.isPwdWrong = false;
      if($scope.config.oldpwd != '123456'){
        $scope.config.isPwdWrong = true;
        return;
      }
      $scope.step++;
      slide($scope.step);
    };
    $scope.finish = function () {
      $scope.config.isPwdSame = true;
      if($scope.config.newpwd != $scope.config.newpwd2){
        $scope.config.isPwdSame = false;
        $scope.config.newpwd = '';
        $scope.config.newpwd2 = '';
        return;
      }
      growlService.growl("密码修改成功！", "success");
      $uibModalInstance.close();
    };

    $scope.config = {
      isPwdWrong: false,
      isPwdSame: true,
      oldpwd: '',
      newpwd: '',
      newpwd2: ''
    };
  })
  .controller('virtualMachineIPCtrl', function ($scope, $uibModalInstance, growlService){
    $scope.cancel = function () {
      $uibModalInstance.dismiss('cancel');
    };

    $scope.finish = function () {
      swal("成功!", "", "success");
      $uibModalInstance.close();
    };

    $scope.data = {
      IPlist: ['192.168.1.101', '192.168.1.102', '192.168.1.103']
    };

    $scope.config = {
      ip: '',
    };
  })
  .controller('virtualMachineUpdateCtrl', function ($scope, $uibModalInstance, growlService){
    $scope.cancel = function () {
      $uibModalInstance.dismiss('cancel');
    };

    $scope.finish = function () {
      growlService.growl("服务器配置修改成功！", "success");
      $uibModalInstance.close();
    };

    $scope.data = {
      networks: ['public', 'private', 'nxtcloud']
    };

    $scope.config = {
      network: '',
      ip: '',
      disks: []
    };
    $scope.ipRegex = '\\d+.\\d+.\\d+.\\d+';
    var indexPool = [0, 1, 2];
    $scope.addDisk = function (){
      $scope.config.disks.push({
        id: indexPool.pop(),
        type: 'disk',
        busType: 'scsi',
        container: 'default',
        size: '',
      })
    }
    $scope.deleteDisk = function (id){
      for(var i = 0; i < $scope.config.disks.length; i++){
        if($scope.config.disks[i].id == id){
          $scope.config.disks.splice(i, 1);
          indexPool.push(id);
          break;
        }
      }
    }
  })
;
 